import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    user: {
      'id': '',
      'name': '',
      'phone': '',
      'sex': '',
      'age': 0,
      'userType': 0,
      'image': '',
      'address': '',
      'createAt': ''
    },
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_User: (state, obj) => {
    state.user = obj
  },
  SET_AVATAR: (state, avatar) => {
    state.user.image = avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { phone, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: phone.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_User', data.user)
        commit('SET_TOKEN', data.token)
        setToken(data.token) // token 保存在cookie中
        sessionStorage.setItem('uid', data.user.id) // 本地存储保存用户id
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 刷新时，由于store会丢失，所以更加id重新查询并复制
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const id = sessionStorage.getItem('uid')
      getInfo(id).then(response => {
        const { data } = response
        if (!data) {
          return reject('验证失败，请重新登陆！')
        }

        commit('SET_User', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

